package com.css.fxfzxczh.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author leon
 * @Title:
 * @Description:文件压缩工具类
 * @date 2020/8/10 17:01
 */
public class ZipUtils {

    private static Logger logger = LoggerFactory.getLogger(com.css.fxfzxczh.common.utils.ZipUtils.class);

    private ZipUtils() {
    }

    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }

    public static byte[] doCompress(String sourceFilePath) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //将目标文件打包成zip导出
        File file = new File(sourceFilePath);
        doCompress(file, zip, "");
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 文件压缩
     *
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();//记得关闭资源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException {
        doCompress(new File(filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException {
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    com.css.fxfzxczh.common.utils.ZipUtils.doCompress(file, out, name);
                }
            }
        } else {
            com.css.fxfzxczh.common.utils.ZipUtils.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        String entryName = null;
        if (!"".equals(dir)) {
            entryName = dir + "/" + inFile.getName();
        } else {
            entryName = inFile.getName();
        }
        ZipEntry entry = new ZipEntry(entryName);
        // 支持中文
        out.setEncoding("GBK");
        out.putNextEntry(entry);

        int len = 0;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }

    public static void doZip(InputStream in, ZipOutputStream out, String entryName) throws IOException {
        logger.info("---添加InputStream到压缩文件，InputStream大小：{}", in.available());
        ZipEntry entry = new ZipEntry(entryName);
        out.setEncoding("GBK");
        out.putNextEntry(entry);
        int len = 0;
        byte[] buffer = new byte[1024 * 5];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        in.close();
    }

    public static void main(String[] args) throws IOException {
        doCompress("E:/view/", "D:/附件.zip");
    }

    public static void exportZip(List<ZipExportWeb> fileList, String responseFileName, HttpServletResponse response) throws FileNotFoundException {
        String rootPath = ResourceUtils.getURL("classpath:").getPath() + File.separator + "cache_file/" + File.separator + IdUtil.simpleUUID();
        FileUtil.mkdir(rootPath);
        for (ZipExportWeb zipExportWeb : fileList) {
            String destName = StringUtils.isNotBlank(zipExportWeb.getFileNewName()) ? zipExportWeb.getFileNewName() + "." + FileUtil.getSuffix(zipExportWeb.getFile()) : zipExportWeb.getFile().getName();
            FileUtil.copy(zipExportWeb.getFile(), new File(rootPath + File.separator + destName), true);
        }
        try (OutputStream out = response.getOutputStream()) {
            byte[] data = doCompress(rootPath);
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "*");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + responseFileName + ".zip");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.flush();
            FileUtil.del(rootPath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static class ZipExportWeb {
        private File file;
        private String fileNewName;

        public ZipExportWeb(File file, String fileNewName) {
            this.file = file;
            this.fileNewName = fileNewName;
        }

        public File getFile() {
            return file;
        }

        public void setFile(File file) {
            this.file = file;
        }

        public String getFileNewName() {
            return fileNewName;
        }

        public void setFileNewName(String fileNewName) {
            this.fileNewName = fileNewName;
        }
    }

}
